package com.zx.tfw.service;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zx.tfw.dao.TechnicalFrameworkDao;
import com.zx.tfw.entity.TechnicalFramework;
import com.zx.tfw.utils.TfwInfoFromIneter;

@Service
public class BatchService {

	@Autowired
	private TechnicalFrameworkDao technicalFrameworkDao;
	
	public void getRemark() {
		final List<TechnicalFramework> all = this.technicalFrameworkDao.findAll();
		int threadNum = 10;
		LinkedBlockingQueue<TechnicalFramework> queue = new LinkedBlockingQueue<>(100);
		
		ExecutorService pool = Executors.newFixedThreadPool(threadNum);
		
		CountDownLatch latch = new CountDownLatch(threadNum);
		
		pool.submit(() -> {
			for (TechnicalFramework tfw : all) {
				try {
					queue.put(tfw);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			latch.countDown();
			
		});
		
		for (int i = 0; i < threadNum - 1; i++) {
			pool.submit(() -> {
				try {
					TechnicalFramework tfw = null;
					while ((tfw = queue.poll(5, TimeUnit.SECONDS)) != null) {
						String remark = TfwInfoFromIneter.getRemark(tfw.getNameAcronym());
						if( !StringUtils.isEmpty(remark)) {
							tfw.setRemark(remark.substring(0, Math.min(1000 * 5, remark.length() ) ));
							this.technicalFrameworkDao.save(tfw);
							System.out.println(tfw.getId() + "~~~~~~~~~~" + remark.length());
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				latch.countDown();
			});
		}
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	
}
